Ext.define('DCApp.controller.Global', {
    extend: 'Ext.app.Controller',
    requires: [
        'DCApp.view.*',
        'Ext.window.*'
    ],
    loadingText: 'Loading...',
    stores: ['Thumbnails','Authors','BFS'],
    config: {
        control: {
        	'#app-header menuitem[text=关于]':{
        		click:'onAbout'
        	},
        	'#app-header menuitem[text=注销]':{
        		click:'onLogoutClick'
        	},
        	'#app-header menuitem[text=Print Label]':{
        		click:'onPrintLabel'
        	},
            'navigation-tree': {
                selectionchange: 'onTreeNavSelectionChange'
            },
            'navigation-breadcrumb breadcrumb': {
                selectionchange: 'onBreadcrumbNavSelectionChange'
            },
            'thumbnails': {
                itemclick: 'onThumbnailClick',
                itemdblclick: 'onThumbnailClick'
            },
            'tool[regionTool]': {
                click: 'onSetRegion'
            },
            'doclist':{
            	openobj:'onOpenObj'
            },
            'docdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'imagelist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Userlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Userdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Tasklist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'Taskdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'imgpanel':{
            	editobj:'onEditObj'
            },
            'imagedetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'CeAttachmentlist':{
            	openobj:'onOpenObj',
            	editobj:'onEditObj'
            },
            'attachpanel':{
            	editobj:'onEditObj'
            },
            'CeAttachmentdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'reliclist':{
            	openobj:'onOpenObj'
            },
            'relicdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'relicelist':{
            	openobj:'onOpenObj'
            },
            'relicedetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'CcSynclist':{
            	openobj:'onOpenObj'
            },
            'CcSyncdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            }
            
        },
        refs: {
            viewport: 'viewport',
            navigationTree: 'navigation-tree',
            navigationBreadcrumb: 'navigation-breadcrumb',
            contentPanel: 'contentPanel',
            descriptionPanel: 'descriptionPanel',
            thumbnails: {
                selector: 'thumbnails',
                xtype: 'thumbnails',
                autoCreate: true
            }
        },
        routes  : {
            ':id': {
                action: 'handleRoute',
                before: 'beforeHandleRoute'
            },
            '(:en)detail/:id':{
            	action     : 'showDetail',
            	conditions111 : {
                    ':id' : '([0-9]+)'
                }
            }
        }
    },
    onPrintLabel:function(item,e,opts){
    	var st = Ext.StoreMgr.get('navigation');
    	var func_print=function(obj){
    		var items = obj.items;
    		if(items){    			
    			for(var i=0; i<items.length; i++){
    				func_print(items[i]);
    			}
    		}else{
    			if(obj.fieldLabel){
    				console.log(obj.fieldLabel+':'+obj.bind);
    			}    			
    		}
    	};
    	st.each(function(rec){
    		var nl = rec.id;
    		if(nl.indexOf('list')==-1)
    			return;
	     	var nd = nl.replace('list','detail');
	     	var className = Ext.ClassManager.getNameByAlias('widget.'+nd);
	        var ViewClass = Ext.ClassManager.get(className);
 			if(!ViewClass)
 				return;
 			console.group('-----------'+rec.get('text')
 				+'['+Ext.String.capitalize(nl.substring(0,nl.length-4))+']'
 				+'-------------');
    		func_print(ViewClass.prototype);
    		console.groupEnd();
    	},this);
    },
    onLogoutClick:function(item,e,opts){
    	var me=this;
    	Ext.MessageBox.confirm('确认注销', '真的要舍我而去吗?',
			function(btn, text) {
				if (btn != 'yes')
					return false;
			me.loginManager.logout();
    	});
    },
    onAbout:function(item,e){
    	Ext.MessageBox.show({
			title:'关于', 
			icon: Ext.MessageBox.INFO,
			animEl:item,
			msg:'<p align=\'center\'>'+DCApp.Cfg.APP_NAME+DCApp.Cfg.ABOUT+'</p>',
			buttons: Ext.MessageBox.OK,
			width:220
		});
    },
    setOrigUri:function(uri){
    	this.ouri = uri;
    },
    getOrigUri:function(){
    	return this.ouri;
    },
    showDetail:function(p1,p2,p3){
		//console.log('showDetail:'+p1+":"+p3);
		var me=this;
		if(me.open_info){
			return me.openObj();
		}
		var pdetail = p1+'detail';
		if(!DCApp.Cfg.usrInfo){
			me.setOrigUri(pdetail+'/'+p3);
			return me.showLogin();
		}
		var className = 'DCApp.model.'+Ext.String.capitalize(p1);
    	var modelClass = Ext.ClassManager.get(className);
    	//不符合detail命名规则的走VIP通道
    	if(!modelClass){
    		modelClass=Ext.ClassManager.get('DCApp.model.'+detailCMap[p1]);
    	}
    	if(!modelClass)
    		return false;
    	var pm={};
    	pm[modelClass.idProperty||'id']=parseInt(p3);
    	var obj = modelClass.create(pm);
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,p3,pdetail);
    	    }
    	});
    	
    },
    
    onEditObj:function(vw,rec){
    	
    	var vm = vw.getViewModel();
     	var nd = vm.type.replace('list','detail');
     	var ds = vw.getStore();
        var className = Ext.ClassManager.getNameByAlias('widget.'+nd);
        var ViewClass = Ext.ClassManager.get(className);

    	var cmp = new ViewClass({viewModel: {
            data: {
            	theObj: rec,
            	showprev:false,
            	shownext:false,
            	showsave:true && !DCApp.Cfg.bView,
            	showpayCalculate:true && !DCApp.Cfg.bView,
            	showreturn:false
            }
        }});    
    	
     	var dlg = Ext.create('Ext.window.Window', {
     		scrollable :true,
     		maximized:true,
     		//layout: 'fit',
     		items:[cmp],
     		listeners:{
     			close:function(win,eopts){
     				vw.detail_open=false;
     			}
     		}
    	});
     	dlg.show();
     	vw.detail_open=true;
    },
    onOpenObj:function(vw,rec,action){
    	//var vm = vw.getViewModel();
    	//var nd = this.getView().getXType().replace('detail','list');
    	var nl = vw.getXType();
     	var nd = nl.replace('list','detail');
     	var ds = vw.getStore();
     	var pos = ds.indexOf(rec);
     	if(pos==-1){
     		rec.set('id',-1);
     	}
     	
     	this.open_info={
     		list:vw,
     		rec:rec,
     		nd:nd,nl:nl,
     		rec_prev : ds.getAt(pos-1),
     		rec_next : ds.getAt(pos+1),
     		scroll_y : vw.getView().getScrollY(),
     		action:action
     	};
    	this.redirectTo(nd + '/'+ rec.id);
    },
    objNext:function(){
    	//destroy current detail panel
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(true);
    	
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_next;
     	var pos = ds.indexOf(rec);
     	inf.rec_prev= inf.rec;
     	inf.rec=inf.rec_next;
     	inf.rec_next = ds.getAt(pos+1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    objPrev:function(){
    	//destroy current detail panel
    	var contentPanel = this.getContentPanel();
    	contentPanel.removeAll(true);

    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_prev;
     	var pos = ds.indexOf(rec);
     	inf.rec_next= inf.rec;
     	inf.rec=inf.rec_prev;
     	inf.rec_prev = ds.getAt(pos-1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },

      
    
    viewObj:function(rec,id,detail_type){
    	var contentPanel = this.getContentPanel();
    	var myMask = new Ext.LoadMask({
    	    msg    : '正在打开',
    	    target : contentPanel
    	});
    	myMask.show();
    	contentPanel.removeAll(true);
        var className = Ext.ClassManager.getNameByAlias('widget.'+detail_type);
        var ViewClass = Ext.ClassManager.get(className);

    	var cmp = new ViewClass({viewModel: {
            data: {
            	theObj: rec,
            	showprev:false,
            	shownext:false,
            	showsave:false,
            	showpayCalculate:false,
            	showreturn:false
            }
        }});    	
    	cmp.masker = myMask;
    	contentPanel.add(cmp);
    	Ext.resumeLayouts(true);
    },
    openObj:function(){
    	var contentPanel = this.getContentPanel();
    	var myMask = new Ext.LoadMask({
    	    msg    : '正在打开',
    	    target : contentPanel
    	});

    	myMask.show();
    	this.grid_hides = contentPanel.removeAll(false);
    	var list = this.open_info.list;
    	var cmp = list.detail;
    	if(!cmp){
	        var className = Ext.ClassManager.getNameByAlias('widget.'+this.open_info.nd);
	        var ViewClass = Ext.ClassManager.get(className);
	
	    	cmp = new ViewClass({viewModel: {
	            data: {
	            	theObj: this.open_info.rec,
	            	showprev:Boolean(this.open_info.rec_prev),
	            	shownext:Boolean(this.open_info.rec_next),
	            	showsave:true&& !DCApp.Cfg.bView,
	            	showpayCalculate:true&& !DCApp.Cfg.bView,
	            	showreturn:true
	            }
	        }});    
	       // list.detail=cmp;
    	}else{
	        cmp.getViewModel().bind({data: {
	            	theObj: this.open_info.rec
	            }},function(d){
	        	//console.log(d);
	        });
	        cmp.updateLayout();
    	}
        //建立list与对应detail的双向指向，以支持detail的返回 下一条，detail的直接复用。
        cmp.masker = myMask;
    	contentPanel.add(cmp);
    },

    beforeHandleRoute: function(id, action) {
        var me = this;
    	if(!me.user){
    		me.setOrigUri(id);
    		me.showLogin();
    		return false;
    	}
        var node = Ext.StoreMgr.get('navigation').getNodeById(id);

        if (node) {
            //resume action
            action.resume();
        } else {
            Ext.Msg.alert(
                'Route Failure',
                'The view for ' + id + ' could not be found. You will be taken to the application\'s start',
                function() {
                    me.redirectTo(me.getApplication().getDefaultToken());
                }
            );

            //stop action
            action.stop();
        }
    },

    handleRoute: function(id) {
    	var me = this;
        var navigationTree = me.getNavigationTree(),
            navigationBreadcrumb = me.getNavigationBreadcrumb(),
            store = Ext.StoreMgr.get('navigation'),
            node = store.getNodeById(id),
            contentPanel = me.getContentPanel(),
            themeName = Ext.themeName,
            thumbnails = me.getThumbnails(),
            hasTree = navigationTree && navigationTree.isVisible(),
            cmp, className, ViewClass, clsProto, thumbnailsStore;

        Ext.suspendLayouts();

        if (node.isLeaf()) {
        	var b_return=this.open_info && id== this.open_info.nl;
            if (thumbnails.ownerCt) {
                contentPanel.remove(thumbnails, false); // remove thumbnail view without destroying
            } else {
            	contentPanel.removeAll(true);
            	//彻底销毁隐藏并提供给‘返回’复用的grid
            	if(!b_return && this.grid_hides){
            		var ghs = this.grid_hides;
            		for(var i=0; i<ghs.length; i++){
            			ghs[i].close();
            		}
            		delete this.grid_hides;
            	}
            }

            if (hasTree) {
                // Focusing explicitly brings it into rendered range, so do that first.
                navigationTree.getView().focusNode(node);
                navigationTree.getSelectionModel().select(node);
            } else {
                navigationBreadcrumb.setSelection(node);
            }

			if(b_return){
				cmp = this.open_info.list;
			}else{
	            className = Ext.ClassManager.getNameByAlias('widget.' + id);
	            ViewClass = Ext.ClassManager.get(className);
	            //判断view是否存在，防止不存在的view导致后续view调度失效
	            if(!ViewClass){
	            	Ext.resumeLayouts(true);        
	            	return;
	            }
	            clsProto = ViewClass.prototype;
	
	            if (clsProto.themes) {
	                clsProto.themeInfo = clsProto.themes[themeName];
	
	                if (themeName === 'gray') {
	                    clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes.classic);
	                } else if (themeName !== 'neptune' && themeName !== 'classic') {
	                    if (themeName === 'crisp-touch') {
	                        clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes['neptune-touch']);
	                    }
	                    clsProto.themeInfo = Ext.applyIf(clsProto.themeInfo || {}, clsProto.themes.neptune);
	                }
	                // <debug warn>
	                // Sometimes we forget to include allowances for other themes, so issue a warning as a reminder.
	                if (!clsProto.themeInfo) {
	                    Ext.log.warn ( 'Example \'' + className + '\' lacks a theme specification for the selected theme: \'' +
	                        themeName + '\'. Is this intentional?');
	                }
	                // </debug>
	            }
	
	            cmp = new ViewClass();
			}
            contentPanel.add(cmp);
            this.updateTitle(node);
            
            if(!b_return){
            	Ext.resumeLayouts(true);            	
            }
            else{
            	Ext.resumeLayouts(true);
            	//偏移1像素,否则gridview不刷新
            	if(this.open_info.action=='ACTION_NEW'){
            		//父类List已统一处理
            		//cmp.getView().scrollTo(0,0);
            		cmp.getView().getStore().load();
            	}else{
            		cmp.getView().scrollTo(0,this.open_info.scroll_y+1);
            	}
            }

            if (cmp.floating) {
                cmp.show();
            }
        } else {
            // Only attempt to select the node if the tree is visible
            if (hasTree) {
                if (id !== 'all') {
                    // If the node is the root (rootVisible is false), then
                    // Focus the first node in the tree.
                    navigationTree.ensureVisible(node.isRoot() ? store.getAt(0) : node, {
                        select: true,
                        focus: true
                    });
                }
            }
            // Ensure that non-leaf nodes are still highlighted and focused.
            else {
                navigationBreadcrumb.setSelection(node);
            }
            thumbnailsStore = me.getThumbnailsStore();
            thumbnailsStore.removeAll();
            thumbnailsStore.add(node.childNodes);
            if (!thumbnails.ownerCt) {
                contentPanel.removeAll(true);
            }
            //contentPanel.setLayout('auto');
            contentPanel.add(thumbnails);
            this.updateTitle(node);
            Ext.resumeLayouts(true);
        }
    },
    
    updateTitle: function(node) {
        var text = node.get('text'),
            title = node.isLeaf() ? (node.parentNode.get('text') + ' - ' + text) : text;
        
        this.getContentPanel().setTitle(title);
        document.title = document.title.split(' - ')[0] + ' - ' + text;
    },


    exampleRe: /^\s*\/\/\s*(\<\/?example\>)\s*$/,
    themeInfoRe: /this\.themeInfo\.(\w+)/g,

    renderCodeMarkup: function(loader, response) {
        var code = this.processText(response.responseText, loader.themeInfo);
        // Passed in from the block above, we keep the proto cloned copy.
        loader.resource.html = code;
        loader.getTarget().setHtml(code);
        //prettyPrint();
        return true;
    },

    processText: function (text, themeInfo) {
        var lines = text.split('\n'),
            removing = false,
            keepLines = [],
            len = lines.length,
            exampleRe = this.exampleRe,
            themeInfoRe = this.themeInfoRe,
            encodeTheme = function (text, match) {
                return Ext.encode(themeInfo[match]);
            },
            i, line, code;

        for (i = 0; i < len; ++i) {
            line = lines[i];
            if (removing) {
                if (exampleRe.test(line)) {
                    removing = false;
                }
            } else if (exampleRe.test(line)) {
                removing = true;
            } else {
                // Replace "this.themeInfo.foo" with the value of "foo" properly encoded
                // for JavaScript (otherwise strings would not be quoted).
                line = line.replace(themeInfoRe, encodeTheme);
                keepLines.push(line);
            }
        }

        code = Ext.htmlEncode(keepLines.join('\n'));
        return '<pre class="prettyprint">' + code + '</pre>';
    },

    onSetRegion: function (tool) {
        var panel = tool.toolOwner;

        var regionMenu = panel.regionMenu || (panel.regionMenu =
            Ext.widget({
                xtype: 'menu',
                items: [{
                    text: 'North',
                    checked: panel.region === 'north',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('north');
                    }
                },{
                    text: 'South',
                    checked: panel.region === 'south',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('south');
                    }
                },{
                    text: 'East',
                    checked: panel.region === 'east',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('east');
                    }
                },{
                    text: 'West',
                    checked: panel.region === 'west',
                    group: 'mainregion',
                    handler: function () {
                        panel.setBorderRegion('west');
                    }
                }]
            }));

        regionMenu.showBy(tool.el);
    },

    onTreeNavSelectionChange: function(selModel, records) {
    	if(this.open_info){
    		delete this.open_info;
    	}
        var record = records[0];

        if (record) {
            this.redirectTo(record.getId());
        }
    },

    onBreadcrumbNavSelectionChange: function(breadcrumb, node) {
        if (node) {
            this.redirectTo(node.getId());
        }
    },

    onThumbnailClick: function(view, node, item, index, e) {
        var navigationTree = this.getNavigationTree();

        // If not using breadcrumb nav, drive the app through the tree's normal selection listener
        // This ensures that the tree is scrolled correctly with the correct node highlighted.
        if (navigationTree && navigationTree.isVisible()) {
            navigationTree.ensureVisible(node, {
                select: true,
                focus: true
            });
        } else {
        	var idd = node.data['idd'];
        	if(idd)
        		idd+='/-1';
            this.redirectTo(idd||node.getId());
        }
    },
    onLogin: function (view, user,  loginManager) {
		if (this.login) {
			this.login.destroy();
			delete this.login;
		}
		this.loginManager = loginManager;
        //this.organization = organization;
        this.user = user;
        
        this.showUI(view);
    },
    
    showUI: function(view) {
        Ext.create('DCApp.store.Navigation', {
            storeId: 'navigation'
        });
/*        Ext.create('Ext.data.ArrayStore', {
		    storeId: 'st_userlist',
		    pageSize: 100,
		    autoLoad :true,
		    model: 'DCApp.model.UGroup',
			proxy : {  
    	    	type: 'reste',
    	        url: '/list/UGroup',
    	    	reader :
    	        {  
    				type : 'json',  
    				rootProperty : 'data',
    				totalProperty:'total'
    	        }
    	    }     		    
		});
*/    	var me = this;
        me.viewport = new DCApp.view.main.Main({
            session: this.session,
            viewModel: {
                data: {
                    currentOrg: this.organization,
                    currentUser: this.user
                }
            }
        });
        var url = me.getOrigUri()||'all';
        //不是通过login窗口登录的之后会有route来到，不需要重复调用redirectTo
        if(view)
        	me.redirectTo(url,true);
    },
    showLogin:function(){
    	if(this.login)
			return;
		this.login = new DCApp.view.login.Login({
			session: this.session,
			autoShow: true,
			listeners: {
				scope: this,
				login: 'onLogin'
			}
        });
    },
    onLaunch: function () {
		var me = this;
		var token = Ext.util.Cookies.get("accessToken");
		if ((token != null) && (token != "")) {
			if (!me.loginManager) {
				me.loginManager = new DCApp.LoginManager({
					session: null,
					model: 'User'
				});
			}
			var data={accessToken:token};
			me.loginManager.login({
				data: data,
				scope: me,
				success: function(user){
					var hash = window.location.hash;
					if((hash != null) && (hash != "") && (hash.length>0)) {
						hash = hash.substring(1);
						me.setOrigUri(hash);
					}
					this.onLogin(null, user, me.loginManager);
				},
				failure: function(){
					me.showLogin();
				}
			});
		} else {
			me.showLogin();
		}
    }

});
